package com.lcf.framework.utils;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.constant.SysConstant;
import com.lcf.system.entity.SysTenantUser;

import java.util.Objects;

import static com.lcf.framework.constant.SysConstant.DEFAULT_TENANT_ID;

/**
 * 描述：用户工具类
 *
 * @author lcf
 * @since 2025/2/27 14:41
 */
public class UserUtils {
    private static final ThreadLocal<Long> TENANT_ID_HOLDER = new ThreadLocal<>();

    /**
     * 获取当前登录用户id
     */
    public static long getUserId() {
        return ServletUtils.getRequest() != null && StpUtil.isLogin() ? StpUtil.getLoginIdAsLong() : 0L;
    }

    /**
     * 获取租户id
     */
    public static long getTenantId() {
        Long tenantId = TENANT_ID_HOLDER.get();

        if (tenantId == null) {
            SysTenantUser sysTenantUser = Db.lambdaQuery(SysTenantUser.class).eq(SysTenantUser::getUserId, UserUtils.getUserId()).one();
            setTenantId(sysTenantUser == null ? DEFAULT_TENANT_ID : sysTenantUser.getTenantId());
        }

        return TENANT_ID_HOLDER.get();
    }

    /**
     * 是否平台管理员
     */
    public static boolean isPlatformAdmin() {
        return Objects.equals(getUserId(), SysConstant.PLATFORM_ADMIN_ID);
    }

    /**
     * 密码明文转密文
     */
    public static String passwordEncrypt(String password) {
        return SaSecureUtil.md5(password + SysConstant.PASSWORD_SALT);
    }

    /**
     * 设置租户id
     */
    public static void setTenantId(long tenantId) {
        TENANT_ID_HOLDER.set(tenantId);
    }

    /**
     * 清除租户id
     */
    public static void clearTenantId() {
        TENANT_ID_HOLDER.remove();
    }
}
